//
//  NewAddressViewController.m
//  AppleMarket
//
//  Created by yangy on 08/11/2018.
//  Copyright © 2018 szgsy. All rights reserved.
//

#import "NewAddressViewController.h"
// model
#import "CoinAssetModel.h"
#import "ImageCodeMoel.h"
// view
#import "BH_UnderLineTextField.h"
// controller
#import "InputCodeViewController.h"
#import "SafePwdAlterViewController.h"

@interface NewAddressViewController ()
@property (nonatomic, strong) UILabel *titleLabel;
@property (nonatomic, strong) BH_UnderLineTextField *addressTF; // 地址
@property (nonatomic, strong) BH_UnderLineTextField *commenTF;  // 备注
@property (nonatomic, strong) BH_UnderLineTextField *codeTF;    // 邮箱短信验证码
@property (nonatomic, strong) UIButton *commitButton;           // 提交
@property (nonatomic, strong) NSString *addressStr_;
@property (nonatomic, strong) NSString *commoenStr_;
@property (nonatomic, strong) NSString *codeStr_;
@property (nonatomic, strong) NSString *pwdStr_;
@property (nonatomic, assign) NSInteger time;                   // 发送验证码倒计时
@property (nonatomic, strong) RACDisposable *disposable;
@end

@implementation NewAddressViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    [self initViews];
    [self bindViewMOdel];
}

- (void) bindViewMOdel
{
    RAC(self,addressStr_) = _addressTF.rac_textSignal;
    RAC(self,commoenStr_) = _commenTF.rac_textSignal;
    RAC(self,codeStr_) = _codeTF.rac_textSignal;
    
    RAC(_commitButton,enabled) = [RACSignal combineLatest:@[RACObserve(_addressTF, text),RACObserve(_commenTF, text),RACObserve(_codeTF, text)] reduce:^id (NSString *address,NSString *commoen,NSString *code){
        return @(address.length && commoen.length && code.length);
    }];
    RAC(_commitButton,backgroundColor) = [RACSignal combineLatest:@[RACObserve(_addressTF, text),RACObserve(_commenTF, text),RACObserve(_codeTF, text)] reduce:^id (NSString *address,NSString *commoen,NSString *code){
        return (address.length && commoen.length && code.length)? kColorWithHex(0x3291EB) : kColorWithHex(0xADB7C1);
    }];
}

- (void) request_SendMsgCode:(NSString*) key code:(NSString*) imageCode
{
    NSString *account = [PlistCommon loginModel].IsMobile? [PlistCommon loginModel].PhoneNumber : [PlistCommon loginModel].Email;
    [SVProgressHUD show];
    [NetRequest request_SendMsgCodeType:@"AddWithdrawAddr" account:account code:imageCode key:key completeHandler:^(id  _Nonnull responseObj) {
        if([[responseObj objectForKey:@"Status"] boolValue]){
            [SVProgressHUD showInfoWithStatus:[NSString stringWithFormat:@"验证码已发送至%@%@",[PlistCommon loginModel].IsMobile? @"手机" : @"邮箱",account]];
        }else{
            [SVProgressHUD showInfoWithStatus:[responseObj objectForKey:@"Msg"]];
        }
    } fail:^(NSError * _Nonnull error) {
        [SVProgressHUD showInfoWithStatus:@"网络异常"];
    }];
}

- (void) request_AddNewAddress
{
    [SVProgressHUD show];
    [NetRequest request_DoAddUserWithdrawWithCode:_codeStr_ ceId:self.assetModel.CurrencyID addr:_addressStr_ memo:_commoenStr_ pwd:_pwdStr_ completeHandler:^(id  _Nonnull responseObj) {
        if([[responseObj objectForKey:@"Status"] boolValue]){
            [SVProgressHUD showInfoWithStatus:@"添加成功"];
            [SVProgressHUD dismissWithDelay:3 completion:^{
                if(self.newCompleteHandler){
                    self.newCompleteHandler();
                }
                [self.navigationController popViewControllerAnimated:YES];
            }];
        }else{
            [SVProgressHUD showInfoWithStatus:[responseObj objectForKey:@"Msg"]];
        }
    } fail:^(NSError * _Nonnull error) {
        [SVProgressHUD showInfoWithStatus:@"网络异常"];
    }];
}

- (void) initViews
{
    [self.view addSubview:self.titleLabel];
    [self.view addSubview:self.addressTF];
    [self.view addSubview:self.commenTF];
    [self.view addSubview:self.codeTF];
    [self.view addSubview:self.commitButton];
    [self setViewLayout];
}

- (void) setViewLayout
{
    [_titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(self.view).offset(30);
        make.top.mas_equalTo(self.view.mas_top).offset(29);
    }];
    
    [_addressTF mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.titleLabel.mas_bottom).offset(70);
        make.left.mas_equalTo(self.titleLabel);
        make.right.mas_equalTo(self.view.mas_right).offset(-30);
    }];
    
    [_commenTF mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(self.addressTF);
        make.right.mas_equalTo(self.addressTF);
        make.top.mas_equalTo(self.addressTF.mas_bottom).offset(18);
    }];
    
    [_codeTF mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(self.addressTF);
        make.right.mas_equalTo(self.addressTF);
        make.top.mas_equalTo(self.commenTF.mas_bottom).offset(18);
    }];
    
    [_commitButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.codeTF.mas_bottom).offset(45);
        make.left.mas_equalTo(self.addressTF);
        make.right.mas_equalTo(self.addressTF);
        make.height.mas_equalTo(40);
    }];
}

- (UILabel *)titleLabel
{
    if(!_titleLabel){
        NSString *text = [NSString stringWithFormat:@"添加%@钱包地址",self.assetModel.Unit];
        _titleLabel = [UILabel cm_labelWithText:text font:kFontBold(26) textColor:kColorWithHex(0x0E304C)];
    }
    return _titleLabel;
}

- (BH_UnderLineTextField *)addressTF
{
    if(!_addressTF){
        _addressTF = [[BH_UnderLineTextField alloc] init];
        _addressTF.placeholder = @"输入或长按粘贴地址";
        _addressTF.font = kFont(13);
    }
    return _addressTF;
}

- (BH_UnderLineTextField *)commenTF
{
    if(!_commenTF){
        _commenTF = [[BH_UnderLineTextField alloc] init];
        _commenTF.placeholder = @"标签，如：Bianca地址";
        _commenTF.font = kFont(13);
    }
    return _commenTF;
}

- (BH_UnderLineTextField *)codeTF
{
    if(!_codeTF){
        _codeTF = [[BH_UnderLineTextField alloc] init];
        _codeTF.placeholder = @"请输入验证码";
        _codeTF.font = kFont(13);
        _codeTF.rightViewMode = UITextFieldViewModeAlways;
        _codeTF.rightText = @"获取验证码";
        _codeTF.rightTextFont = kFont(13);
        _codeTF.rightTextColor = kColorWithHex(0x3291EB);
        @weakify(self);
        _codeTF.rightHanlder = ^{
          // 点击获取验证码
            @strongify(self);
            UIButton *sendButton = (UIButton*)self.codeTF.rightView;
            sendButton.enabled = NO;
            self.time = 60;
            self.disposable = [[RACSignal interval:1.0 onScheduler:[RACScheduler mainThreadScheduler]] subscribeNext:^(NSDate * _Nullable x) {
                self.time -- ;
                NSString *title = self.time > 0 ? [NSString stringWithFormat:@"%lds",self.time] : @"重新发送";
                UIColor *bgColor =  self.time > 0 ? kColorWithHex(0xADB7C1) : kColorWithHex(0x3291EB);
                [sendButton setTitle:title forState:UIControlStateNormal | UIControlStateDisabled];
                [sendButton setTitleColor:bgColor forState:UIControlStateNormal | UIControlStateDisabled];
                sendButton.enabled = (self.time <= 0) ? YES : NO;
                if(self.time == 0){
                    [self.disposable dispose];
                }
            }];
            InputCodeViewController *codeVC = [InputCodeViewController inputCodeViewControllerWithCodeType:CodeTypeAddWithdrawAddr];
            codeVC.view.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.85];
            codeVC.modalPresentationStyle = UIModalPresentationOverCurrentContext;
            codeVC.completeHandler = ^(ImageCodeMoel * _Nonnull codeModel,NSString *inputCodeStr) {
                [self request_SendMsgCode:codeModel.ImgKey code:inputCodeStr];
            };
            [self presentViewController:codeVC animated:YES completion:nil];
        };
    }
    return _codeTF;
}

- (UIButton *)commitButton
{
    if(!_commitButton){
        _commitButton = [UIButton cm_ButtonWithTitle:@"提交" font:kFont(14) titleColor:[UIColor whiteColor] bgColor:kColorWithHex(0xADB7C1)];
        _commitButton.layer.cornerRadius = 2;
        [[_commitButton rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
            // 弹出资金密码界面
            SafePwdAlterViewController *pwdVC = [[SafePwdAlterViewController alloc] init];
            pwdVC.view.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.85];
            pwdVC.modalPresentationStyle = UIModalPresentationOverCurrentContext;
            pwdVC.completeHandler = ^(NSString * _Nonnull pwdStr_) {
                self.pwdStr_ = pwdStr_;
                // 请求添加新地址接口
                [self request_AddNewAddress];
            };
            [self presentViewController:pwdVC animated:YES completion:nil];
        }];
    }
    return _commitButton;
}

@end
